package cn.xiaolang.thread.concurrent;

/**
 * 等待唤醒机制：
 * 在多生产多消费的情况，但是会出现死锁情况，或者重复商品的现象
 *
 * @author DeanKano
 * @date 2016年12月18日 下午12:59:19
 */
public class ProduceConsumerWaitNotify {

    public static void main(String[] args) {
        //生产者消费者共享的资源
        ShareResource resource = new ShareResource();
        new Thread(new Producer(resource), "P1").start();
        new Thread(new Producer(resource), "P2").start();
        new Thread(new Producer(resource), "P3").start();
        new Thread(new Consumer(resource), "C1").start();
        new Thread(new Consumer(resource), "C2").start();
    }

    /**
     * 生产者
     */
    static class Producer implements Runnable {

        private ShareResource resource;

        Producer(ShareResource resource) {
            this.resource = resource;
        }

        @Override
        public void run() {
            int num = 1;
            while (true) {
                resource.putSyncIfWaitNotify(Thread.currentThread().getName() + num);
                num++;
            }
        }
    }

    static class Consumer implements Runnable {
        private ShareResource resource;

        Consumer(ShareResource resource) {
            this.resource = resource;
        }

        @Override
        public void run() {
            while (true) {
                resource.gainSyncIfWaitNotify();
            }
        }
    }
}





